package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"gitee.com/fu-ce-wei/pi-mapper/internal/config"
	"gitee.com/fu-ce-wei/pi-mapper/internal/task"
	"gitee.com/fu-ce-wei/pi-mapper/pkg/logger"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// setupRouter 创建Gin路由实例
func setupRouter(cfg *config.Config) *gin.Engine {
	// 设置Gin模式
	if cfg.Server.Mode == "release" {
		gin.SetMode(gin.ReleaseMode)
	}

	// 创建Gin路由
	router := gin.New()
	router.Use(gin.Recovery())

	return router
}

// startServer 启动HTTP服务器
func startServer(router *gin.Engine, cfg *config.Config, appLogger *logger.Logger) *http.Server {
	srv := &http.Server{
		Addr:    fmt.Sprintf(":%d", cfg.Server.Port),
		Handler: router,
	}

	// 启动服务器
	go func() {
		appLogger.Info("启动HTTP服务器", zap.Int("port", cfg.Server.Port))
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			appLogger.Fatal("HTTP服务器启动失败", zap.Error(err))
		}
	}()

	return srv
}

// startScheduler 启动定时任务调度器
func startScheduler(services *Services, cfg *config.Config, appLogger *logger.Logger, ctx context.Context) *task.Scheduler {
	scheduler := task.NewScheduler(services.ScanService, services.ImageScanService, cfg, appLogger)

	// 启动定时任务调度器（在HTTP服务器之后启动）
	if err := scheduler.Start(ctx); err != nil {
		appLogger.Error("启动定时任务调度器失败", zap.Error(err))
	}

	return scheduler
}

// gracefulShutdown 优雅关闭服务器
func gracefulShutdown(srv *http.Server, scheduler *task.Scheduler, appLogger *logger.Logger) {
	// 等待中断信号以优雅关闭服务器
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	appLogger.Info("收到停止信号，开始优雅关闭...")

	// 创建关闭上下文
	shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer shutdownCancel()

	// 停止定时任务调度器
	appLogger.Info("停止定时任务调度器...")
	if scheduler != nil {
		scheduler.Stop()
	}

	// 关闭HTTP服务器
	appLogger.Info("关闭HTTP服务器...")
	if err := srv.Shutdown(shutdownCtx); err != nil {
		appLogger.Error("HTTP服务器关闭失败", zap.Error(err))
	}

	appLogger.Info("应用已优雅关闭")
}
